package com.ionehe.group.common.wechat.component;

import cn.hutool.core.util.StrUtil;
import com.ionehe.group.common.wechat.config.WechatConfig;
import com.ionehe.group.common.wechat.exception.WechatException;
import com.ionehe.group.common.wechat.model.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 微信访问token缓存
 *
 * @author 2022/1/7 <a href="mailto:a@ionehe.com">xiu</a>
 */
@Component
@Slf4j
public class WechatRequestAccessTokenCache {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private WechatAPI wechatAPI;
    private static final Integer duration = 60;
    private static final String wechatAccessToken = "wechat:accessToken";

    public String findAccessToken(WechatConfig config) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String accessToken = operations.get(wechatAccessToken);

        if (StrUtil.isEmpty(accessToken)) {
            log.info("WechatRequestAccessTokenCache[]findAccessToken[] start to get request access token from WX");

            AccessToken requestAcct = wechatAPI.getRequestAcct(config);
            if (Objects.isNull(requestAcct) || requestAcct.getAccessToken() == null) {
                log.error("WechatRequestAccessTokenCache[] findAccessToken[]get request access token null error");
                throw new WechatException("accessToken null error");
            }

            accessToken = requestAcct.getAccessToken();

            log.info("WechatRequestAccessTokenCache[]findAccessToken[] set request access token to Redis, accessToken:{}", accessToken);
            operations.set(wechatAccessToken, accessToken);
            stringRedisTemplate.expire(wechatAccessToken, duration, TimeUnit.MINUTES);
        } else {
            log.info("WechatRequestAccessTokenCache[]findAccessToken[] get request access token from Redis, accessToken:{}", accessToken);
        }
        return accessToken;
    }
}
